<template>
  <el-dialog width="60%" class="WholeScroll" :visible.sync="formShow" v-dialog-drag :modal="false" :append-to-body="true" :modal-append-to-body="false" :close-on-click-modal="false">
    <span slot="title">
      <i class="iconfont icon-zhiliangguanli1"></i>
      <span>{{ title }}</span>
    </span>
    <div class="map-picker-box">
      <div class="flex_align" style="margin-bottom: 15px;">
        <el-input style="flex:1;" size="small" v-model="formBaseData.positionName" placeholder="请输入位置信息"></el-input>
        <el-input v-if="isShowJW" style="width: 17%;margin-left: 10px;" size="small" v-model="formBaseData.JD" placeholder="请输入经度信息"></el-input>
        <el-input v-if="isShowJW" style="width: 17%;margin-left: 10px;" size="small" v-model="formBaseData.WD" placeholder="请输入纬度信息"></el-input>
        <el-button class="dialog-normal-button" @click="confirmPosition()">确认选择</el-button>
      </div>
      <div id="mapCorner"></div>
    </div>
  </el-dialog>
</template>

<script>
export const centerLng = 112.53;
export const centerLat = 32.99;
import { getOnePicDataByType } from '@/api/buss/mapdata'
import { computeCenterAndZoom } from '@/utils/map';

export default {
  name: 'positonPicker',
  data() {
    return {
      title: '地图点位拾取',
      formShow: false,
      mmap: '',
      projectId: '',
      satellite: null,
      roadNet: null,
      formBaseData: {
        positionName: '',
        JD: '',
        WD: '',
      },
    }
  },
  props: {
    postDetail: {
      type: Object,
      default: {
        show: false,
        type: 'build',
        params: {}
      }
    },
    isShowJW: {
      type: Boolean,
      default: true
    }
  },
  watch: {
    postDetail(value) {
      this.formShow = value.show
      if (value.projectId) {
        this.projectId = value.projectId
        this.getProjectLine(this.projectId)
      }
    }
  },
  mounted() {
  },
  methods: {
    getProjectLine(id) {

      return getOnePicDataByType({
        typeList: ['项目路线图']
      }).then(res => {

        if (res.data.hasOwnProperty('项目路线图')) {
          res.data['项目路线图'].forEach((d, index) => {

            if (d.projectWorkInfo && d.projectId == id) {
              // this.addPolyline(d.projectWorkInfo.projectInfoObj['线路图'], d);
              this.initMap(d.projectWorkInfo.projectInfoObj['线路图'])
            }
            if (!d.projectWorkInfo && d.projectId == id) {

              this.initMap('', [120.50, 30.08])
            }
          })
        }
        return new Promise(resolve => {
          resolve(res)
        })
      }).catch(res => {
        console.log(res)
      })
    },
    //画线的起点和终点
    addStartEndline(lineData) {
      const startMyIcon = new AMap.Icon({
        image: require('@/assets/images/cockpit/3_17Map/yellow.png'),
        size: new AMap.Size(6, 6),
        imageSize: new AMap.Size(6, 6),
      });
      // 创建标注对象并添加到地图
      let startPosition = [lineData[0].lng, lineData[0].lat];
      let endPosition = [lineData[lineData.length - 1].lng, lineData[lineData.length - 1].lat];
      AMap.convertFrom([startPosition, endPosition], 'baidu', (_, result) => {
        const { info, locations } = result;
        if (info === 'ok' && locations) {
          startPosition = locations[0];
          endPosition = locations[1];
        }
      })
      const startMarker = new AMap.Marker({
        position: startPosition,
        icon: startMyIcon,
        offset: new AMap.Pixel(-3, -3),
        extData: {
          typeName: '线路',
        },
      });

      const endMyIcon = new AMap.Icon({
        image: require('@/assets/images/cockpit/3_17Map/red.png'),
        size: new AMap.Size(6, 6),
        imageSize: new AMap.Size(6, 6),
      });
      // 创建标注对象并添加到地图
      const endMarker = new AMap.Marker({
        position: endPosition,
        icon: endMyIcon,
        offset: new AMap.Pixel(-3, -3),
        extData: {
          typeName: '线路',
        },
      });

      if (this.mmap) {
        this.mmap.add([startMarker, endMarker]);
      }
    },
    //向地图画线
    addPolyline(lineData, projectInfos) {
      const map = this.mmap;
      const vm = this;
      const path = lineData.map((l) => ([l.lng, l.lat]));
      let color = 'rgba(0,0,205,0.3)'
      if (projectInfos) {
        if (projectInfos.projectTypeName == '高速公路') {
          color = 'rgba(0,0,205,1)'
        } else {
          if (projectInfos.gradeTypeName == '国道') {
            color = 'rgba(0,0,205,0.7)'
          } else if (projectInfos.gradeTypeName == '省道') {
            color = 'rgba(0,0,205,0.7)'
          } else if (projectInfos.gradeTypeName == '县道') {
            color = 'rgba(0,0,205,0.7)'
          } else {

          }
        }
      }
      const polyline = new AMap.Polyline({
        path,
        isOutline: false,
        strokeColor: color,
        strokeWeight: 3,
        lineJoin: 'round',
        zIndex: 50,
        extData: {
          orginColor: color,
        },
      });
      // polyline.on('mouseover', (e) => {
      //   polyline.setOptions({
      //     strokeColor: '#01f7e1',
      //   });
      //   const infoWindow = vm.message(projectInfos);
      //   if (infoWindow) {
      //     infoWindow.open(map, e.lnglat);
      //   }
      // });
      // polyline.on('mouseout', () => {
      //   const { orginColor } = polyline.getExtData();
      //   polyline.setOptions({
      //     strokeColor: orginColor,
      //   });
      //   map.clearInfoWindow();
      // });
      polyline.setMap(this.mmap);
    },
    confirmPosition() {
      this.$set(this, 'formShow', false)
      // 传值给父组件刷新列表
      this.$emit('setPosition', this.formBaseData)
    },
    initMap(lineData, markers = []) {
      let that = this
      if (!AMap) return;
      // 初始化地图，设置中心点坐标和地图级别
      let { center, zoom } = {
        center: '',
        zoom: 10
      }
      if (lineData) {
        let { center, zoom } = computeCenterAndZoom(8, lineData);
        if (!AMap) return;
        markers = center
      }

      const map = new AMap.Map('mapCorner', {
        center: markers,
        zooms: [4, 15],
        zoom,
        mapStyle: 'amap://styles/c2ae45a800aa8ad7c39b1eaf5e4dd22a',
        layers: [],
      });
      const cityName = '柯桥区';
      AMap.plugin('AMap.DistrictSearch', () => {
        new AMap.DistrictSearch({
          extensions: 'all',
          subdistrict: 1,
          level: 'city',
        }).search(cityName, (_, result) => {
          const outer = [
            new AMap.LngLat(-360, 90, true),
            new AMap.LngLat(-360, -90, true),
            new AMap.LngLat(360, -90, true),
            new AMap.LngLat(360, 90, true),
          ];
          const { districtList } = result || {};
          if (districtList && districtList.length > 0) {
            const holes = districtList[0].boundaries;
            const pathArray = [outer];
            pathArray.push.apply(pathArray, holes);
            const polygon = new AMap.Polygon({
              path: pathArray,
              strokeColor: 'rgba(192, 242, 239, 1)',
              strokeWeight: 1,
              fillColor: 'rgba(204, 212, 215, 1)',
              fillOpacity: 1,
            });
            polygon.setPath(pathArray);
            map.add(polygon);
          }
        })
      })
      if (lineData) {
        this.mmap = map;
        const path = lineData.map((l) => ([l.lng, l.lat]));
        const polyline = new AMap.Polyline({
          path,
          isOutline: false,
          strokeColor: '#09F007',
          strokeWeight: 6,
          lineJoin: 'round',
        });
        map.add(polyline);
        this.addStartEndline(lineData)
      }


      let marker = new AMap.Marker({
        position: markers//位置
      });
      map.add(marker);
      map.on('click', function (e) {
        console.log(e, 'eeeeeeeeee')
        map.remove(marker);
        that.formBaseData.WD = e.lnglat.getLat();
        that.formBaseData.JD = e.lnglat.getLng();
        marker = new AMap.Marker({
          position: [e.lnglat.getLng(), e.lnglat.getLat()], //标记当前的坐标
          offset: new AMap.Pixel(0, 0) //鼠标与标点的像素偏差值
        });
        AMap.plugin('AMap.Geocoder', function () {
          var geocoder = new AMap.Geocoder({
            // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
          })

          var lnglat = [that.formBaseData.JD, that.formBaseData.WD]

          geocoder.getAddress(lnglat, function (status, result) {
            if (status === 'complete' && result.info === 'OK') {
              // result为对应的地理位置详细信息
              console.log(result, 'result')
              that.formBaseData.positionName = result.regeocode.formattedAddress ? result.regeocode.formattedAddress : '--'
            }
          })
        })
        map.add([marker]);
        markers.push(marker);
      });
      this.satellite = new AMap.TileLayer.Satellite()
      this.roadNet = new AMap.TileLayer.RoadNet()
    },
  },
}
</script>

<style scoped lang="scss">
#mapCorner {
  width: 100%;
  height: 600px;
  background-color: #999999;
}
.flex_align {
  display: flex;
  flex-direction: row;
  align-items: center;
}
.dialog-normal-button {
  margin-left: 15px;
}
</style>
